Visualizing objects that manage program flow.
An **Iterator** is an object with a `next()` method that returns a result object `{ value: ..., done: true/false }` on each call, enabling sequential access to items in a collection. An **AsyncIterator** is similar but its `next()` method returns a promise that resolves to the result object, allowing for iteration over asynchronous data.
const iterable = [1, 2, 3]; const iterator = iterable[Symbol.iterator](); iterator.next(); // { value: 1, done: false }
An iterator is a pointer that moves through a list, one item at a time.
A **Promise** object represents the eventual completion (or failure) of an asynchronous operation and its resulting value. An **AsyncFunction** is a function that always returns a promise and can use the `await` keyword to pause execution until a promise is resolved.
async function fetchData() { const response = await fetch('url'); return response.json(); }
A promise is like a coupon for a future result. It can be in one of three states: pending, fulfilled, or rejected.
A **GeneratorFunction** is a special kind of function that can be paused and resumed. It returns a **Generator** object, which is an iterator. When the `next()` method is called, the generator runs until it hits a `yield` statement, which pauses execution and returns a value.
function* count() { yield 1; yield 2; yield 3; } const gen = count();
A generator is like a function that can "remember" where it left off, and be controlled step-by-step.
These new objects from ES2023 provide a mechanism for managing resources that need to be cleaned up. A **DisposableStack** calls a cleanup function for each item when the stack is `disposed`. An **AsyncDisposableStack** works similarly but for asynchronous cleanup.
const stack = new DisposableStack(); stack.use({ [Symbol.dispose]() { console.log('Cleanup!'); } }); stack.dispose();
A disposable stack is a to-do list for cleaning up resources. When the list is disposed, each task is performed in reverse order.